package com.xjl.example.aqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * Created by xiaojinlu1990@163.com on 2019/11/30.
 * Semaphore (信号量控制线程数) 尝试获取许可  核心方法（适用场景： ）
 * 1 acquire();//获取一个许可
 * 2  release();//释放一个许可
 * 3
 *
 */
public class SemaphoreExmaple3 {

    private static Logger log = LoggerFactory.getLogger(CountDownLatch.class);

    public final static int clienttotal = 500;
    public final static int threadTotal = 3;
    public static int count = 0;


    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);

        for (int i = 0; i < clienttotal; i++) {
            executor.execute(() ->{
                try {
                    if(semaphore.tryAcquire(5000, TimeUnit.MICROSECONDS)){  //尝试获取许可
                        add();
                        semaphore.release();//释放一个许可
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
        }
        log.info("finish!!!");
        executor.shutdown();
    }

    private static void add() {
        try {
            Thread.sleep(1001);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count++;
        log.info("{}",count);
    }


}
